package com.feinno.urcs.group.siptask;

import com.feinno.urcs.group.servlet.GroupMemberDialog;
import com.feinno.urcs.group.servlet.GroupMemberDialogHasOffline;
import com.feinno.urcs.group.servlet.GroupServlet;
import com.feinno.urcs.group.siptask.task.GroupMessageArgs;
import com.feinno.urcs.group.siptask.task.GroupTaskEvents;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.TaskImplementation;
import org.helium.framework.task.DedicatedTask;
import org.helium.framework.task.DedicatedTaskContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Lei Gao on 7/4/15.
 */
@TaskImplementation(event = GroupTaskEvents.GROUP_SESSION_MODE_MESSAGE)
public class GroupSessionMessageTask implements DedicatedTask<GroupMessageArgs> {

	private static final Logger LOGGER = LoggerFactory.getLogger(GroupSessionMessageTask.class);
	@FieldSetter("group:GroupServlet")
	private GroupServlet servlet;

	public GroupSessionMessageTask() {

	}

	public GroupSessionMessageTask(GroupServlet servlet) {
		this.servlet = servlet;
	}

	@Override
	public void processTask(DedicatedTaskContext ctx, GroupMessageArgs args) {
		try {
			LOGGER.info(String.format("GroupSessionMessageTask args=%s", args.toJsonObject()));
			GroupMemberDialog dialog = (GroupMemberDialog) ctx.getSession(GroupServlet.TASK_CONTEXT_NAME);
			if (args.isOnlyActiveOfflineMsg()) {
				LOGGER.info("GroupSessionMessageTask isOnlyActiveOfflineMsg. " + args.toJsonObject().toString());
				if (dialog != null) dialog.closeDialog();
				servlet.activateMember(args);
				ctx.setTaskRunnable();
				return;
			}
	/*如果这里已经存在dialog,
	 是不是很奇怪?已经有dialog 了.
	 不需要重新激活了吧? 或者说其实用户已经断线了,不管了 交给,交给dialog 处理  */
			LOGGER.info("GroupSessionMessageTask Pattern ." + args.toJsonObject().toString());
			String message = new String(args.getContent());
			Matcher m = Pattern.compile("<Font.*?>([\\s\\S]*?)</Font>").matcher(message);
			while (m.find()) {
				message = m.group(1).trim();
			}

			if (dialog == null) {
				//没有dialog 的时候, 先把当前消息离线,然后激活, 当前消息走离线了..
				LOGGER.info("GroupSessionMessageTask activateAndSendMessage " + args.toJsonObject().toString());
				servlet.activateAndSendMessage(ctx, args, true);
				ctx.setTaskRunnable();
				return;
			}

			if (dialog.isClean()) {
				LOGGER.info("GroupSessionMessageTask isClean activateAndSendMessage " + args.toJsonObject().toString());
				servlet.activateAndSendMessage(ctx, args, true, dialog);
				ctx.setTaskRunnable();
				return;
			}

			servlet.sendText(dialog,
					args.getFromMobile(),
					args.getContentType(),
					args.getGroupMessageStorageId(),
					message.getBytes());
			ctx.setTaskRunnable();
		} catch (Exception e) {
			LOGGER.error("GroupSessionMessageTask error " + args.toJsonObject().toString(), e);
		}
	}

	@Override
	public void processTaskRemoved(DedicatedTaskContext ctx) {
		servlet.close(ctx);
	}
}
